package com.zhuoyue.listener;

import com.zhuoyue.biz.core.api.service.GatewayRedisService;
import com.zhuoyue.common.utils.CmdUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author Administrator
 */
@Component
@RabbitListener(queues = "${topic.rabbit.deviceRemoveGroup}")
public class DeviceDeleteGroup {

    @Autowired
    private GatewayRedisService gatewayRedisService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 消息处理
     */
    @RabbitHandler
    public void clearDeviceDelGroup(Map<String, String> getMap) {
        String deviceMac = getMap.get("deviceMac");
        String gatewayMac = getMap.get("gatewayMac");
        String cmd = clearGroup(deviceMac, gatewayMac);
        if (StringUtils.isNotEmpty(cmd)) {
            gatewayRedisService.writeDataToGateway(gatewayMac, cmd);
        } else {
            System.out.println("clearDeviceDelGroup数据清空失败");
        }
    }

    private String clearGroup(String deviceMac, String gatewayMac) {
        String randomCode = RandomStringUtils.randomNumeric(4);
        String cmdStr = "52" + "00" + gatewayMac + "06" + randomCode + "01" + deviceMac;
        String dateLength = CmdUtils.getDateLength(cmdStr);
        String cmdBodySum = CmdUtils.getCmdBodySum(cmdStr);
        stringRedisTemplate.opsForValue().set(gatewayMac + "_" + randomCode, deviceMac, 10, TimeUnit.SECONDS);
        return "2A" + dateLength + cmdStr + cmdBodySum + "23";
    }

}
